package xs.szw.service.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import xs.szw.service.utils.SecurityUtils;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * @program: xs_oa
 * @description: mybatis-plus 字段自动填充 createBy createTime updateBy updateTime
 * @author: Songzw
 * @create: 2025-02-14 19:37
 **/
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
    /***
     * 新增时 填充字段数据
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            if(SecurityUtils.getLoginUserId() != null){
                this.strictInsertFill(metaObject, "createBy", Long.class, SecurityUtils.getLoginUserId());
            }else {
                log.warn("创建人 ID 为空，无法填充 createBy 字段");
            }
            this.strictInsertFill(metaObject, "createTime", LocalDateTime::now,LocalDateTime.class);
        }catch (Exception e){
                log.error("插入时字段填充失败", e);
        }

    }

    /**
     * 修改时 填充字段数据
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        try{
            if(SecurityUtils.getLoginUserId() != null){
                this.strictUpdateFill(metaObject, "updateBy", Long.class,SecurityUtils.getLoginUserId());
            }else{
                log.warn("更新人 ID 为空，无法填充 updateBy 字段");
            }
            this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now,LocalDateTime.class);
        }catch (Exception e){
            log.error("更新时字段填充失败", e);
        }
    }
}
